import json
import time
from app.extensions import redis, rq_queue
from app.ws.connection import connection_manager
from app.services.message import MessageService
from app.services.user import UserService
from app.utils.response import APIResponse

class WSMessageHandler:
    def __init__(self):
        self.handlers = {
            'heartbeat': self.handle_heartbeat,
            'private_message': self.handle_private_message,
            'group_message': self.handle_group_message,
            'read_receipt': self.handle_read_receipt,
            'typing': self.handle_typing
        }
    
    def handle(self, connection_id, message):
        try:
            data = json.loads(message)
            msg_type = data.get('type')
            handler = self.handlers.get(msg_type)
            
            if handler:
                return handler(connection_id, data)
            else:
                return APIResponse.error(message="未知的消息类型")
        except json.JSONDecodeError:
            return APIResponse.error(message="无效的JSON格式")
        except Exception as e:
            return APIResponse.error(message=f"处理消息失败: {str(e)}")
    
    def handle_heartbeat(self, connection_id, data):
        """处理心跳消息"""
        user_id = connection_manager.connection_users.get(connection_id)
        if user_id:
            # 更新用户最后活跃时间
            rq_queue.enqueue(
                UserService.update_last_seen,
                user_id,
                job_timeout=3
            )
        return APIResponse.success(message="pong")
    
    def handle_private_message(self, connection_id, data):
        """处理私聊消息"""
        user_id = connection_manager.connection_users.get(connection_id)
        if not user_id:
            return APIResponse.error(message="未认证的连接")
        
        receiver_id = data.get('receiver_id')
        content = data.get('content')
        msg_type = data.get('message_type', 'text')
        
        if not receiver_id or not content:
            return APIResponse.error(message="缺少必要参数")
        
        # 异步处理消息发送
        rq_queue.enqueue(
            MessageService.send_private_message,
            user_id,
            receiver_id,
            content,
            msg_type,
            job_timeout=5
        )
        
        return APIResponse.success(message="消息已接收处理")
    
    def handle_group_message(self, connection_id, data):
        """处理群聊消息"""
        user_id = connection_manager.connection_users.get(connection_id)
        if not user_id:
            return APIResponse.error(message="未认证的连接")
        
        group_id = data.get('group_id')
        content = data.get('content')
        msg_type = data.get('message_type', 'text')
        
        if not group_id or not content:
            return APIResponse.error(message="缺少必要参数")
        
        # 异步处理消息发送
        rq_queue.enqueue(
            MessageService.send_group_message,
            user_id,
            group_id,
            content,
            msg_type,
            job_timeout=5
        )
        
        return APIResponse.success(message="群消息已接收处理")
    
    def handle_read_receipt(self, connection_id, data):
        """处理已读回执"""
        user_id = connection_manager.connection_users.get(connection_id)
        if not user_id:
            return APIResponse.error(message="未认证的连接")
        
        message_ids = data.get('message_ids')
        if not message_ids:
            return APIResponse.error(message="缺少消息ID列表")
        
        # 异步处理已读标记
        rq_queue.enqueue(
            MessageService.mark_as_read,
            message_ids,
            user_id,
            job_timeout=3
        )
        
        return APIResponse.success(message="已读回执已接收")
    
    def handle_typing(self, connection_id, data):
        """处理正在输入状态"""
        user_id = connection_manager.connection_users.get(connection_id)
        if not user_id:
            return APIResponse.error(message="未认证的连接")
        
        receiver_id = data.get('receiver_id')
        is_group = data.get('is_group', False)
        
        if not receiver_id:
            return APIResponse.error(message="缺少接收者ID")
        
        typing_message = {
            'type': 'typing',
            'sender_id': user_id,
            'receiver_id': receiver_id,
            'is_group': is_group,
            'timestamp': int(time.time())
        }
        
        if is_group:
            # 群聊中发送给所有成员
            from app.services.group import GroupService
            members = GroupService.get_group_members(receiver_id)
            for member in members:
                if member['user_id'] != user_id:  # 不发送给自己
                    connection_manager.send_to_user(member['user_id'], typing_message)
        else:
            # 私聊直接发送给对方
            connection_manager.send_to_user(receiver_id, typing_message)
        
        return APIResponse.success(message="正在输入状态已发送")

ws_message_handler = WSMessageHandler()